<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
      <uni-forms-item name="deviceId" required>
				<view class="mTitle">
					设备编号
				</view>
        <uni-easyinput v-model="formData.deviceId" ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="content" required>
				<view class="mTitle">
					故障描述（限200字以内）
				</view>
        <uni-easyinput v-model="formData.content" type="textarea"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="img">
				<view class="mImg">
					<uni-file-picker
						v-model="formData.img"
						limit="1" fileMediatype="image" 
						title="最多可以上传1张现场图片"
						@select="select" 
						@progress="progress" 
						@success="success" 
						@fail="fail"
						></uni-file-picker>
				</view>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" @click="submit">提交</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/breaks.js';

  const db = uniCloud.database();
  const dbCollectionName = 'breaks';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "deviceId": "",
        "subtime": null,
        "content": "",
        "img": []
      }
      return {
        formData,
				imgUrl:"",
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
		onLoad(e) {
			console.log(e)
		  if(e.deviceId){
				this.formData.deviceId = e.deviceId
			}
		},
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
			select(e){
				console.log('选择文件：',e)
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功',e)
				this.imgUrl = e.tempFilePaths[0]
				console.log("imgUrl:",this.imgUrl)
				// var imgitem = {}
				// imgitem.id = e.tempFiles[0].image.__ob__.dep.id
				// imgitem.url = e.tempFiles[0].url
				
				// this.formData.img.push(imgitem)
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			},
			
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
				value.img[0] = this.imgUrl
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            icon: 'none',
            title: '新增成功'
          })
					//这里增加对pc-info表的更新操作
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() =>{
						uni.redirectTo({
							url:"/pages/pc-info/list"
						})
					}, 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>

<style>
  .uni-container {
    padding: 15px;
  }

  .uni-input-border,
  .uni-textarea-border {
    width: 100%;
    font-size: 14px;
    color: #666;
    border: 1px #e5e5e5 solid;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .uni-input-border {
    padding: 0 10px;
    height: 35px;

  }

  .uni-textarea-border {
    padding: 10px;
    height: 80px;
  }
	
	.mImg{
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

  .uni-button-group {
    margin-top: 50px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
  }

  .uni-button {
    width: 184px;
  }
</style>
